package com.black.aidl.client;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;

import com.black.aidl.IMyIPCInterface;
import com.black.aidl.User;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "aidl_client";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Intent intent = new Intent("com.black.aidl.IMyIPCInterface");
        intent.setPackage("com.black.aidl.service");
        bindService(intent, connection, BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        unbindService(connection);
    }

    private IMyIPCInterface manager = null;

    private final ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            manager = IMyIPCInterface.Stub.asInterface(service);
            if (manager != null) {
                try {

                    User user = new User("Tom", "Boy", 12);
                    Log.i(TAG, "onServiceConnected: user: " + user.toString());

                    int userAge = manager.writeAndReadAge(user.getAge());
                    Log.i(TAG, "onServiceConnected: after: " + userAge);
                    String userName = manager.writeAndReadName(user.getName());
                    Log.i(TAG, "onServiceConnected: userName: " + userName);
                    manager.writeAndReadUser(user);
                    Log.i(TAG, "onServiceConnected: after " + user.toString());
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            manager = null;
        }
    };
}